<template>
	<picker :value="value" mode="multiSelector" :range="range" range-key="channel_name" @change="change"
		@columnchange="columnchange">
		<fui-form-item label="获客渠道" asterisk arrow highlight>
			<view v-if="value.length === 0" class="fs-color__label">请选择</view>
			<view v-else>{{ label }}</view>
		</fui-form-item>
	</picker>
</template>

<script setup>
	import { onMounted, ref, watch } from 'vue';
	import { fetchChannel } from '@/common/api/index.js';

	const channel_id = defineModel('channel_id');

	const range = ref([
		[],
		[]
	]);
	const value = ref([]);


	async function getLevel1() {
		const data = [
			{ channel_name: '常规非渠道', id: 0, children: [] },
			{ channel_name: '内部商机渠道', id: 1, children: [] },
			{ channel_name: '外部商机渠道', id: 2, children: [] }
		];
		range.value.splice(0, 1, data);
		await getChannel(data[0].id, 0);
	}

	async function getChannel(id, value) {
		const { success, data } = await fetchChannel(id);
		if (success) {
			range.value.splice(1, 1, Array.isArray(data) ? data : []);
			range.value[0][value].children = Array.isArray(data) ? data : []
		}
	}

	const columnchange = async ({ detail: { column, value } }) => {
		if (column === 0) {
			range.value.splice(1, 1, [])
			const obj = range.value[0][value]
			if (obj.children.length === 0) {
				const id = range.value[0][value].id
				await getChannel(id, value);
			} else {
				const arr = range.value[0][value].children
				range.value.splice(1, 1, arr)
			}
		}
	};

	const change = (e) => {
		value.value = e.detail.value;
	};

	const label = ref('');
	watch(
		value,
		(val) => {
			if (val.length === 2) {
				const typeLabel = range.value[0][val[0]].channel_name;
				const channelLabel = range.value[1][val[1]].channel_name;
				const channelId = range.value[1][val[1]].id;
				label.value = `${typeLabel}--${channelLabel}`;
				channel_id.value = channelId;
			}
		}, { immediate: true }
	);

	onMounted(async () => {
		await getLevel1();
		// 编辑 回显选择
		if (channel_id.value) {
			for (let i = 0; i < range.value[0].length; i++) {
				if (range.value[0][i].children.length === 0) {
					await getChannel(i, i);
				}
				const list = range.value[0][i].children
				const index = list.findIndex((em) => em.id === channel_id.value);
				if (index !== -1) {
					value.value = [i, index];
					break;
				}
				if (i === 2) {
					const arr = range.value[0].children
					range.value.splice(1, 1, arr);
				}
			}
		}
	})
</script>

<style></style>